<template>
  <div class="app-container">
    <div class="components-container">
      <fieldset>
        <el-form ref="contract_form" :rules="contractFormRules" :model="contract_form" label-width="120px"
          label-position="right">
          <el-row>
            <el-col :span="12">
              <el-form-item label="客户名称：" prop="customer_id">
                <el-select v-model="contract_form.customer_id" :disabled="loginType !== 1" style="width: 100%"
                  filterable placeholder="请选择客户" @change="setCustomerId">
                  <el-option v-for="item in customer_options" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同类型：" prop="contract_category">
                <el-select v-model="contract_form.contract_category" :disabled="loginType !== 1" style="width: 100%"
                  filterable clearable placeholder="请选择合同类型">
                  <el-option v-for="item in option_contract_category" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同名称：" prop="contract_name">
                <el-input v-model="contract_form.contract_name" placeholder="合同名称" :disabled="loginType !== 1"
                  maxlength="20" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同编号：" prop="contract_code">
                <el-input v-model="contract_form.contract_code" placeholder="自动生成" maxlength="20" show-word-limit
                  disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="外部合同编号：" prop="contract_external_code">
                <el-input v-model="contract_form.contract_external_code" placeholder="外部合同编号"
                  :disabled="loginType !== 1" maxlength="100" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="签订时间：" prop="contract_sign_date">
                <el-date-picker v-model="contract_form.contract_sign_date" type="date" :disabled="loginType !== 1"
                  format="yyyy-MM-dd" placeholder="选择签订时间" value-format="timestamp" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="text-align: right;">
            <el-button type="primary" size="small" v-show="(this.loginType === 1 && this.isEdit) || !this.isEdit"
              @click="submitCustomerForm('contract_form')">保存
            </el-button>
          </el-row>
        </el-form>
      </fieldset>

      <fieldset>
        <el-tabs type="border-card" @tab-click="tabsHandleClick">
          <el-tab-pane label="事项记录">
            <el-row style="text-align: left;padding: 5px 5px;">
              <el-button type="primary" size="mini" v-show="(this.loginType === 1 && this.isEdit) || !this.isEdit" round
                @click="openContractDialog(1)">新建
              </el-button>
            </el-row>
            <el-table :data="eventTableData" :header-cell-style="{ background: '#F5F5F5', color: '#000' }" height="250"
              style="width: 100%;">
              <el-table-column type="index" :index="computeTableIndex" label="序号" />
              <el-table-column prop="event_content" label="内容" />
              <el-table-column prop="create_date" label="操作时间">
                <template slot-scope="scope">
                  <span>{{ scope.row.create_date | formatSQLDateFormatYMD }}</span>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog title="事项记录" :visible.sync="dialogChangeContractEventFormVisible" :close-on-click-modal="false"
              :close-on-press-escape="false" :destroy-on-close="true" :append-to-body="true"
              @close="dialogChangeContractEventFormVisible = false">
              <el-card class="box-card">
                <el-form :model="changeContractEventForm">
                  <el-form-item label="事项内容：">
                    <el-input v-model="changeContractEventForm.event_content" type="textarea" resize="none" />
                  </el-form-item>
                  <el-form-item style="text-align: right;">
                    <el-button type="primary" @click="saveContractEvent">保存</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-dialog>

          </el-tab-pane>
          <el-tab-pane label="合同附件">
            <el-row style="text-align: left;padding: 5px 5px;">
              <el-button type="primary" size="mini" v-show="(loginType === 1 && isEdit) || !isEdit" round
                @click="openContractDialog(2)">新建
              </el-button>
            </el-row>
            <el-table :data="accessoryTableData" :header-cell-style="{ background: '#F5F5F5', color: '#000' }"
              height="250" style="width: 100%;">
              <el-table-column type="index" :index="computeTableIndex" label="序号" />
              <el-table-column prop="file_name" label="附件名称" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <a :href="getFileLookUrl(scope.row.file_path)" target="_blank">
                    <span>查看</span>
                  </a>
                  <a size="small" v-down-load="scope.row.file_path + '|' + scope.row.file_name">下载</a>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog title="合同附件" :visible.sync="dialogChangeContractAccessoryFormVisible"
              :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true"
              :append-to-body="true" @close="dialogChangeContractAccessoryFormVisible = false">
              <el-card class="box-card">
                <el-upload ref="upload" action style="display:inline-block" :limit="1"
                  accept=".pdf, .doc, .docx, .xls, .xlsx,.png,.jpg" :file-list="fileList" :http-request="uploadImg"
                  :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary" plain>选取文件</el-button>
                  <el-button style="margin-left: 10px;" size="small" icon="el-icon-upload2" type="success"
                    @click="submitUpload">导入
                  </el-button>
                </el-upload>
              </el-card>
            </el-dialog>
          </el-tab-pane>
        </el-tabs>
      </fieldset>
    </div>
  </div>
</template>

<style>
fieldset {
  border: 1px solid #e6ebf5;
  margin: 10px 0 10px 0;
}

legend {
  font-size: 13px;
  padding: 0 10px 0 10px;
}

.el-input__inner {
  height: 30px;
  line-height: 30px;
}

.el-table {
  font-size: 13px;
}

.el-form-item__error {
  display: none;
}

.el-form-item {
  margin-bottom: 0;
}


.el-table th,
.el-table td {
  padding: 5px 0;
}
</style>
<script>
import downLoad from '@/down-load-url'
import { customerSelect } from '@/api/customer'
import {
  addContract,
  contractDetail,
  CreateContractAccessory, CreateContractEvent,
  GetContractAccessoryList,
  GetContractEventList
} from '@/api/contract'
import store from '@/store'
import { uploadFile } from '@/api/qiniu'
import { formatDate } from '@/utils/date'

const defaultForm = {
  id: undefined,
  customer_id: '', // 客户id
  customer_name: '', // 客户姓名
  contract_name: '', // 合同名称
  contract_category: '', //合同类型
  contract_code: '', // 合同编号
  contract_external_code: '', // 外部合同号
  contract_sign_date: '' // 合同签订时间
}

export default {
  name: 'ContractDetail',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  directives: { downLoad },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    formatSQLDateFormatYMD(time) {
      const date = new Date(time * 1000)
      return formatDate(date, 'yyyy-MM-dd')
    }
  },
  data() {
    return {
      loginType: 0,
      contract_id: '',
      contract_form: Object.assign({}, defaultForm),
      loading: false,
      timeNow: new Date(),
      option_contract_category: [
        { value: 1, label: '法律顾问合同' },
        { value: 2, label: '争议解决合同' },
        { value: 3, label: '框架合作合同' },
        { value: 4, label: '非诉项目合同' },
        { value: 0, label: '其他' }],
      customer_options: [],
      contractFormRules: {
        customer_id: [
          { required: true, message: '请选择客户信息', trigger: 'change' }
        ],
        contract_name: [
          { required: true, message: '合同名称不能为空', trigger: 'blur' }
        ],
        contract_external_code: [
          { required: true, message: '外部合同号不能为空', trigger: 'blur' }
        ],
        contract_sign_date: [
          { required: true, message: '合同签订时间不能为空', trigger: 'blur' }
        ]
      },
      eventTableData: [],
      accessoryTableData: [],
      fileList: [],
      dialogChangeContractEventFormVisible: false,
      dialogChangeContractAccessoryFormVisible: false,
      changeContractEventForm: {
        event_content: ''
      }
    }
  },
  created() {
    this.getCustomerSelect()
    this.loginType = store.getters.loginType
    if (this.isEdit) {
      const contractId = this.$route.params && this.$route.params.contractId
      this.fetchData(contractId)
    }
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    getFileLookUrl(imgPath) {
      return 'http://www.wzjip.cn:1180/api/preview?previewUrl=' + encodeURIComponent(imgPath)
    },
    checkPicture(imgPath) {
      //判断是否是图片 - strFilter必须是小写列举
      const strFilter = '.jpeg|.gif|.jpg|.png|.bmp|.pic|.svg|'
      if (imgPath.indexOf('.') > -1) {
        const p = imgPath.lastIndexOf('.')
        let strPostfix = imgPath.substring(p, this.length) + '|'
        strPostfix = strPostfix.toLowerCase()
        if (strFilter.indexOf(strPostfix) > -1) {
          return true
        }
      }
      return false
    },
    computeTableIndex(index) {
      return index + 1
    },
    setCustomerId(value) {
      let obj = {}
      obj = this.customer_options.find((item) => {//model就是上面的数据源
        if (item.value === value) {
          this.contract_form.customer_name = item.label
        }
      })
    },
    getCustomerSelect() {
      const that = this
      customerSelect().then(res => {
        that.customer_options = res.data
      })
    },
    fetchData(contractId) {
      contractDetail(contractId).then(response => {
        this.contract_form = response.data
        this.contract_form.customer_id = this.contract_form.customer_id.toString()
        this.setTagsViewTitle()
        this.getEventList()
      }).catch(err => {
        console.log(err)
      })
      this.contract_id = contractId
    },
    setTagsViewTitle() {
      const title = '编辑合同'
      const route = Object.assign({}, this.tempRoute, { title: `${title}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
      document.title = `${title}`
    },
    submitCustomerForm(formName) {
      let message = '合同创建成功'
      if (this.isEdit) {
        message = '合同更新成功'
      }
      this.contract_form.customer_id = parseInt(this.contract_form.customer_id)
      this.loading = true
      addContract(this.contract_form).then(res => {
        this.loading = false
        console.log(res)
        this.$notify({
          title: '成功',
          message: message,
          type: 'success',
          duration: 2000
        })
        this.contract_form.customer_id = this.contract_form.customer_id.toString()
      }).catch(() => {
        this.contract_form.customer_id = this.contract_form.customer_id.toString()
      })
      this.loading = false
    },
    tabsHandleClick(tab, event) {
      if (tab.index === '0') {
        this.getEventList()
      } else if (tab.index === '1') {
        this.getAccessoryList()
      }
      console.log('11111', tab, event)
    },
    openContractDialog(objType) {
      if (objType === 2) {
        this.dialogChangeContractAccessoryFormVisible = true
        this.getAccessoryList()
      } else if (objType === 1) {
        this.dialogChangeContractEventFormVisible = true
        this.getEventList()
      }
    },
    getEventList() {
      const that = this
      GetContractEventList(that.contract_id).then(response => {
        that.eventTableData = response.data
      }).catch(() => {
        that.eventTableData = []
      })
    },
    getAccessoryList() {
      const that = this
      GetContractAccessoryList(that.contract_id).then(response => {
        that.accessoryTableData = response.data
      }).catch(() => {
        that.accessoryTableData = []
      })
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    uploadImg(fileObj) {
      const that = this
      const formData = new FormData()
      formData.set('file', fileObj.file)
      this.loading = true
      uploadFile(formData, {
        headers: {
          'Content-type': 'multipart/form-data'
        }
      }).then(res => {
        this.loading = false
        const dataParam = {
          contract_id: parseInt(this.contract_id),
          file_id: parseInt(res.data)
        }
        CreateContractAccessory(dataParam).then(res => {
          that.loading = false
          that.$notify({
            title: '成功',
            message: res.message || '更新成功',
            type: 'success',
            duration: 2000
          })
          that.getAccessoryList()
        })
        that.dialogChangeContractAccessoryFormVisible = false
      }
      ).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    saveContractEvent() {
      const dataParam = {
        contract_id: parseInt(this.contract_id),
        event_content: this.changeContractEventForm.event_content
      }
      this.loading = true
      CreateContractEvent(dataParam).then(res => {
        this.loading = false
        this.$notify({
          title: '成功',
          message: res.message || '更新成功',
          type: 'success',
          duration: 2000
        })
        this.getEventList()
        this.changeContractEventForm.event_content = ''
      })
      this.dialogChangeContractEventFormVisible = true
    }
  }
}
</script>
